package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.ir.LiteralNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result querytypelist() {
        //1.查询redis缓存
        List<String> shopTypeListInRedis=stringRedisTemplate.opsForList().range(SHOP_TYPE_KEY,0,-1);
        //2.判断是否存在
        if(!shopTypeListInRedis.isEmpty()){
            //3.存在就返回
            shopTypeListInRedis.stream().map(item->{
                return JSONUtil.toBean(item,ShopType.class);
            }).collect(Collectors.toList());
        }
        //4.不存在，查数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        List<String> resList=typeList.stream().map(item->{
            return JSONUtil.toJsonStr(item);
        }).collect(Collectors.toList());
        //5.将查询出来写入redis
        stringRedisTemplate.opsForList().rightPushAll(SHOP_TYPE_KEY,resList);
        //6.将查询结果返回
        return Result.ok(typeList);
    }
}
